from Crypto.Cipher import AES
import base64

key = b'MSBEcA7UbsniV73K'

def pad(data):
    block_size = AES.block_size
    padding_length = block_size - len(data) % block_size
    return data + bytes([padding_length]) * padding_length

def unpad(data):
    padding_length = data[-1]
    return data[:-padding_length]

def aes_encrypt(data, key):
    cipher = AES.new(key, AES.MODE_ECB)
    encrypted_data = cipher.encrypt(pad(data))
    return encrypted_data

def aes_decrypt(encrypted_data, key):
    cipher = AES.new(key, AES.MODE_ECB)
    decrypted_data = cipher.decrypt(encrypted_data)
    return unpad(decrypted_data)

def base64_encode(data):
    if not isinstance(data, str):
        raise TypeError("Data must be a string")
    data_bytes = data.encode('utf-8')
    encrypted_data = aes_encrypt(data_bytes, key)
    encoded_bytes = base64.b64encode(encrypted_data)
    encoded_str = encoded_bytes.decode('utf-8')
    return encoded_str

def base64_decode(encoded_data):
    if not isinstance(encoded_data, str):
        raise TypeError("Encoded data must be a string")
    encoded_bytes = encoded_data.encode('utf-8')
    decoded_bytes = base64.b64decode(encoded_bytes)
    decrypted_data = aes_decrypt(decoded_bytes, key)
    decrypted_str = decrypted_data.decode('utf-8')
    return decrypted_str

if __name__ == "__main__":
    original_data = '{"timestamp":1716523256728,"productId":"101","eventContent":{"eventTime":1716523256726,"type":3,"signal":39,"battery":4,"imei":"868995060075779","lockState":1,"speed":0,"dir":0,"locType":0,"lat":0,"lng":0,"warnType":6,"reportId":10,"serverRespondId":5598,"assetId":"3502330031","version":"V005","baseStationInfo":{"network":"LTE","bts":"460,00,10173,46371585,35,0","nearbts":"460,01,30518,25306352,46,0|460,00,10173,180441869,45,0|460,00,10173,45957891,38,0|460,00,10173,46703627,35,0|460,00,10173,9529963,34,0","macs":"94:D9:B3:6D:D4:8F,-95,SLY888,-1|BC:3D:85:94:43:B8,-92,YK_APPLE_1,-1|94:D9:B3:6D:D0:E7,-84,SLY666,-1|68:77:24:AB:99:ED,-68,PTWSMART,-1|2C:B2:1A:2C:C7:36,-93,6062,-1|68:DD:B7:2A:54:5F,-74,PTWSMART,-1|72:DD:B7:2A:54:5F,-87,<Hidden SSID>,-1|72:77:24:AB:99:ED,-68,<Hidden SSID>,-1|C2:B9:2A:6E:47:57,-97,DeccTest,-1|2C:61:04:A8:00:0A,-79,3D-08,-1"}}}\r\n'
    # print(f"Original data: {original_data}")

    encoded_ = base64_encode(original_data)
    print(f"Encoded data: {encoded_}")

    encoded = 'ZnXycAaD7Oz9raPygPZJzV/ljFnbsCF7+JZQqijM4o2eJQJSe2gWJuGDIVQejZKD/LkO6A8BZUDBPEijJUIJ7oxTUhLEiIySifx1txHwET80ro7ixQr+eBwz60d1uhQCGa+MlJHsguFN9YmXv4p3KleahQgePuvKrfdiQ4F92fe+x00sbIjm7xtZ+OhUl5tvIZiB2XiWVUiKlgNnsCW24nD3HOJfaAfbLOE0ivu9aEY='
    decoded = base64_decode(encoded)
    print(f"Decoded data: {decoded}")
